package my;

/**
 * 尾调用、尾递归
 *
 * @author AJun
 * @date 2020/11/15
 */
public class TailCall {

    public static void main(String[] args) {
        int n = 5;
        test1(n);
        test2(n);
    }

    static void test1(int n) {
        if (n < 0) return;
        System.out.println("test - " + n);
        test1(n - 1);
    }

    static void test2(int n) {
        if (n < 0) return;
        while (n >= 0) {
            System.out.println("test - " + n);
            n--;
        }
    }

    /**
     * 阶乘
     */
    int factorial(int n) {
        if (n <= 1) return n;
        return n * factorial(n - 1);
    }

    /**
     * 阶乘: 改为尾递归
     */
    int factorial1(int n) {
        return factorial1(n, 1);
    }

    int factorial1(int n, int result) {
        if (n <= 1) return result;
        return factorial1(n - 1, n * result);
    }

    /**
     * 斐波那契数列尾递归
     */
    int fib(int n) {
        return fib(n, 1, 1);
    }

    private int fib(int n, int first, int second) {
        if (n <= 1) return first;
        return fib(n - 1, second, first + second);
    }

}
